<!--
 * @Author: @Edwin
 * @Date: 2020-12-20 10:25:23
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-09 10:42:14
 * @FilePath: \cang-chu-guan-li-xi-tong\src\components\common\stockManagement.vue
-->
<!-- 
所有页面的生成单据信息的组件

接受参数: 
对话框标题
单据表格列
物品表格列
原单名称: 如销售原单、采购原单等


返回的参数: 原单数据

-->
<template>
  <div>
    <!-- 原单生成按钮和表格 -->
    <a-button type="primary" @click="showModal">
      <a-icon type="plus" />
      根据{{ Modal }}生成
    </a-button>
    <a-modal
      :title="ModalTitle"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      width="70%"
    >
      <!-- 搜索表单---查询条件 -->
      <a-form v-bind="layout">
        <a-row>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="时间期间">
              <a-range-picker
                v-model="searchForm.rangeDate"
                @change="getRangeTime"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="单据状态">
              <a-select v-model="searchForm.documentClosed" style="width: 100%">
                <a-select-option
                  v-for="item in documentClosedList"
                  :key="item"
                  :value="item"
                >
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <!-- <a-col
            :xl="8"
            :lg="8"
            :md="8"
            :sm="24"
            :xs="24"
            v-if="stockNoticeShowType"
          >
            <a-form-item label="提报部门">
              <a-tree-select
                v-model="searchForm.reportDept"
                style="width: 100%"
                allow-clear
                :tree-data="deparmentList"
                showSearch
                @change="changeTreeNode"
              >
              </a-tree-select>
            </a-form-item>
          </a-col> -->
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-model-item label="单据编号">
              <a-select
                v-model="searchForm.document"
                showSearch
                style="width: 100%"
              >
                <a-select-option
                  v-for="(item, index) in documentList"
                  :key="index"
                  :value="item"
                >
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="供应商">
              <a-select
                v-model="searchForm.supplier_text"
                @change="getfarmerId"
                @search="getAllfarmerList"
                showSearch
                style="width: 100%"
              >
                <a-select-option
                  v-for="item in supplierList"
                  :key="item.id"
                  :value="item.No + '|' + item.name + '|' + item.id"
                >
                  {{ item.No }} {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24"></a-col>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24"></a-col>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24" align="right">
            <a-button type="primary" @click="Search()">查询</a-button>
            <a-button style="margin-left: 8px" @click="Reset()">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
      <!-- orderColumns  上半部分
listColumns 下半部分 -->
      <!-- 根据源单生产上半部分交互 -->
      <a-table
        style="margin-top: 20px"
        :columns="orderColumns"
        :scroll="{ x: 1000 }"
        :data-source="orderDataSource"
        @change="handleTableChange"
        :pagination="pagination"
        :row-selection="{
          selectedRowKeys: orderSelectedRowKeys,
          onChange: orderOnSelectChange,
          type: 'radio',
          getCheckboxProps: getCheckboxProps,
        }"
      >
        <!-- 审核标志 -->
        <span slot="documentClosed" slot-scope="text, record">
          <a-popconfirm
            title="是否关闭单据?"
            v-if="record.documentClosed == '开启'"
            @confirm="Giorto(record, 1)"
          >
            <a> {{ text }} </a>
          </a-popconfirm>
          <a-popconfirm
            title="是否开启单据?"
            v-if="record.documentClosed == '关闭'"
            @confirm="Giorto(record, 1)"
          >
            <a> {{ text }} </a>
          </a-popconfirm>
        </span>
      </a-table>

      <!-- 下班部分表格 -->
      <a-table
        style="margin-top: 10px"
        :columns="listColumns"
        :data-source="ListDataSource"
        :scroll="{ x: 1500 }"
        :row-selection="{
          selectedRowKeys: listSelectedRowKeys,
          onChange: listOnSelectChange,
          getCheckboxProps: getCheckboxProps,
        }"
      >
        <!-- 审核标志 -->
        <span slot="documentClosed" slot-scope="text, record">
          <a-popconfirm
            title="是否关闭单据?"
            v-if="record.documentClosed == '开启'"
            @confirm="Giorto(record, 2)"
          >
            <a> {{ text }} </a>
          </a-popconfirm>
          <a-popconfirm
            title="是否开启单据?"
            v-if="record.documentClosed == '关闭'"
            @confirm="Giorto(record, 2)"
          >
            <a> {{ text }} </a>
          </a-popconfirm>
        </span>
      </a-table>
    </a-modal>
  </div>
</template>

<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口
//采购入库页面
import { CaiGouRuKuHttp } from "@/services/modules/RuKuGuGuanLi/CaiGouRuKu";
const cgrkHttp = new CaiGouRuKuHttp(); // 采购入库
export default {
  props: {
    // 对话框标题
    ModalTitle: {
      type: String,
      required: true,
    },

    Modal: {
      type: String,
      required: true,
    },
    // 表单列
    orderColumns: {
      type: Array,
      required: true,
    },
    // 列表列
    listColumns: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      supplierList: [], // 供应商

      visible: false,
      documentClosedList: ["开启", "关闭"],
      searchForm: {
        rangeDate: null, // 时间范围
        departmentName: "",
        departmentId: "",
        document: "",
        documentClosed: "开启", //单据状态
        // 采购入库单提报部门
        reportDept: "", // 部门名称
        departmentNo: "", // 部门编号
      },
      pagination: {
        total: 0,
        current: 1,
        pageSize: 5, //每页中显示5条数据
        showSizeChanger: true,
        pageSizeOptions: ["5"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      },

      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 15 },
      },

      // 订单左侧选择框
      orderSelectedRowKeys: [], // 订单选择
      // orderDataSource: [{ key: 1 }],
      orderDataSource: [],

      // 列表左侧选择框
      listSelectedRowKeys: [], // 列表选择
      ListDataSource: [],

      startTime: "", // 开始时间
      endTime: "", // 结束时间
      queryParam: {
        //查询参数
        page: 1, //第几页
        size: 5, //每页中显示数据的条数
        hosName: "",
        hosCode: "",
        province: "",
        city: "",
      },
      stockNoticeShowType: false,
      deparmentList: [], // 部门列表
      SelectData: [], // 选中的值
      originData: [],
      originData2: [],
      queryCache: "",

      savesourceNumber: "", //保存源单号
      saveinventoryId: "", //保存存货id
      savedocumentClosed: "", //保存单据状态上
      saveid: "", //保存id 上
      documentList: [], //单据编号列表
    };
  },
  mounted() {
    this.generateSourceList_back(); //获取采购订单列表
    this.getDocumentList(); //获取单据号列表
  },
  methods: {
    getAllfarmerList(value) {
      if (value != "") {
        comHttp
          .queryByLikeName("?customerName=" + value + "&custflag=1,3")
          .then((res) => {
            this.supplierList = [];
            console.log("所有的供应商信息::::", res);
            for (let i = 0; i < res.result.list.length; i++) {
              let data = {
                No: res.result.list[i].custcode, //编号
                id: res.result.list[i].pkCumandoc,
                name: res.result.list[i].custname,
              };

              this.supplierList.push(data);
            }
          });
        console.log("this.supplierList", this.supplierList);
      }
    },
       // 获取供应商change列表
    getfarmerId(value, options) {
      console.log("供应商::::", value, options.key);
      let array = value.split("|");
      console.log("array", array);
      this.searchForm.supplier = array[2];
      this.searchForm.supplier_text = array[1];
    },
    /**
     //todo 审核标志-单据关闭功能 
     * @description: 审核标志-单据关闭功能
     * @description: 
     * @return
     */
    Giorto(record, select) {
      let that = this;
      console.log(`选中了${select}表格信息`);
      console.log(`选中该记录返回的所有信息:`, record);
      //路线判断
      record.documentClosed === "开启"
        ? goState.call(that, "关闭", record)
        : goState.call(that, "开启", record);

      function goState(status, record) {
        console.log(`正在执行状态${status}功能:::::::::`);
        let data = {
          id: record.id,
          documentClosed: status,
          objectInformationId: record.objectInformationId,
        };
        //接口判断
        return select === 1
          ? this.updatePurchaseaAddorder(data, status)
          : this.updatePurchaseiItemiInformation(data, status);
      }
    },
    //接口关闭-上A
    updatePurchaseaAddorder(data, status) {
      console.log(111);
      cgrkHttp.updateInOrOutStorageOrder(data).then((res) => {
        if (!res.success) {
          this.$message.error(res.message);
          return;
        }
        this.$message.success(`${status}成功!`);
        console.log(`Success::::::${status}功能成功执行`);
        this.generateSourceList_back(); //获取采购订单列表
      });
    },
    //接口关闭-下
    updatePurchaseiItemiInformation(data) {
      let message = {
        id: this.saveid,
        documentClosed: this.savedocumentClosed,
        warehouseObjectInformationEntities: [
          {
            documentClosed: data.documentClosed,
            id: data.objectInformationId,
          },
        ],
      };
      cgrkHttp.updateInOrOutStorageOrderAndGoods(message).then((res) => {
        if (!res.success) {
          this.$message.error(res.message);
          return;
        }
        this.$message.success(`${status}成功!`);
        cgrkHttp
          .getqueryObjectInformationBy("?id=" + this.saveid)
          .then((res) => {
            this.ListDataSource = res.result.list;
          });
      });
    },
    // 表格选择事件,
    // rain-fix:
    // 采购订单生成采购入库单 上面表格的选中事件
    orderOnSelectChange(selectedRowKeys, selectedRows) {
      this.ListDataSource = [];
      this.orderSelectedRowKeys = selectedRowKeys;
      this.orderselectedRows = selectedRows;
      // console.log("selectedRowKeys changed: ", selectedRowKeys);
      console.log("selectedRows changed: ", selectedRows); //获取表格中一行数据
      this.saveid = selectedRows[0].id; //保存id
      this.savedocumentClosed = selectedRows[0].documentClosed; //保存单据状态
      this.savesourceNumber = selectedRows[0].orderNum; //保存源单号
      this.originData2 = selectedRows;

      let id = selectedRows[0].id;
      cgrkHttp.getqueryObjectInformationBy("?id=" + id).then((res) => {
        console.log("采购入库根据源单生成表格选择事件res", res);
        let _data = res.result.list;
        _data.forEach((item, index) => {
          item.key = index + 1;
          item.orderNum = selectedRows[0].orderNum; //保存源单号
          item.documentClosed =
            res.result.list[index].documentClosed == "关闭" ? "关闭" : "开启";
        });
        this.ListDataSource = _data;
      });
    },
    // 列表选择事件 rain:fix 重新进行直接赋值
    listOnSelectChange(selectedRowKeys, selectedRows) {
      // console.log("selectedRowKeys changed: ", selectedRowKeys);
      console.log("下面的表格 selectedRows changed: ", selectedRows); //选中的数据

      // this.saveinventoryId = selectedRows[0].inventoryId;
      this.listSelectedRowKeys = selectedRowKeys;

      this.originData = [];
      for (let i = 0; i < selectedRows.length; i++) {
        this.originData.push(selectedRows[i]);
      }
    },
    // 获取单据号列表
    getDocumentList() {
      let queryPath = "?string=CGRK-";
      cgrkHttp.getDocumentList(queryPath).then((res) => {
        // console.log("获取采购入库单据号列表:::::", res);
        for (let i = 0; i < res.result.length; i++) {
          this.documentList.push(res.result[i]);
        }
      });
    },
    // ---------- 公用函数 ----------
    // 时间段
    getRangeTime(date, dateString) {
      console.log(date);
      this.startTime = dateString[0];
      this.endTime = dateString[1];
    },

    // 搜索
    Search() {
      let query = "";
      if (this.startTime) {
        query += `&beginDate=${this.startTime}`;
      }
      if (this.endTime) {
        query += `&endDate=${this.endTime}`;
      }
      query += `&documentClosed=${this.searchForm.documentClosed}`;
      query += `&document=${this.searchForm.document}`;
      query += `&supplier=${this.searchForm.supplier}`;

      this.queryCache = query;
      this.pagination.current = 1;
      this.pagination.total = 0;
      this.pagination.pageSize = 5;
      this.generateSourceList_back(query);
    },

    // 分页函数
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.generateSourceList_back(this.queryCache);
    },
    // 获取全局查询条件
    getQueryPath() {
      console.log(this.searchForm);
      let queryPath = "?pageNo=" + this.queryParam.page + "&pageSize=5";
      return queryPath; // 返回的查询条件
    },
    // 重置
    // 重置
    Reset() {
      this.saveid = "";
      this.savedocumentClosed = "";
      this.queryCache = "";
      this.pagination.current = 1;
      this.pagination.total = 0;
      this.pagination.pageSize = 5;
      // this.searchForm = {}; // 重置查询条件
      (this.searchForm = {
        rangeDate: null, // 时间范围
        departmentName: "",
        document: "",
        departmentId: "",
        documentClosed: "开启", //单据状态
        // 采购入库单提报部门
        reportDept: "", // 部门名称
        departmentNo: "", // 部门编号
      }),
        this.generateSourceList_back(); // 重置销售订单
      this.listDataSource = []; // 重置物品数据
      this.listSelectedRowKeys = []; // 重置选择框中选中的值
      this.orderSelectedRowKeys = [];
    },
    // 获取采购入库单列表
    // rain-fix:重新进行修改进行多获取
    // rain-fix:删除手动分页
    generateSourceList_back(
      query = `&documentClosed=${this.searchForm.documentClosed}`
    ) {
      console.log("进入采购退库申请的源单列表");
      let _query = "?";
      _query += `pageNo=${this.pagination.current}`;
      _query += `&pageSize=${this.pagination.pageSize}`;
      _query += query;

      cgrkHttp.generateSourceList_back(_query).then((res) => {
        this.orderDataSource = [];
        this.pagination.current = Number(res.result.current);
        this.pagination.total = Number(res.result.total);
        this.pagination.pageSize = Number(res.result.size);
        const startIndex =
          (this.pagination.current - 1) * this.pagination.pageSize;
        for (let i = 0; i < res.result.records.length; i++) {
          let data = {
            key: i + 1 + startIndex,
            id: res.result.records[i].id,
            saleOrderAddId: res.result.records[i].saleOrderAddId,
            document: res.result.records[i].document, //申请单号
            documentDate: res.result.records[i].documentDate, //单据日期
            cbiztype: res.result.records[i].cbiztype, //业务类型id
            cbiztype_dictText: res.result.records[i].cbiztype_dictText, //业务类型
            supplier_dictText: res.result.records[i].supplier_dictText, //供应商
            supplierId: res.result.records[i].supplierId, //供应商
            supplier: res.result.records[i].supplier, //供应商
            supplierId_dictText: res.result.records[i].supplierId_dictText, //供应商
            depotId: res.result.records[i].depotId, //仓库名称
            depotId_dictText: res.result.records[i].depotId_dictText, //仓库名称
            pkCalbody: res.result.records[i].pkCalbody, //库存组织
            pkCalbody_dictText: res.result.records[i].pkCalbody_dictText, //库存组织
            documentClosed:
              res.result.records[i].documentClosed == "关闭" ? "关闭" : "开启", //审核标志
            // buyer: res.result.records[i].buyer, //采购员id
            // buyer_dictText: res.result.records[i].buyer_dictText, //采购员
            // orderNum: res.result.records[i].orderNumb, // 订单编号
            // dateOfPreparation: res.result.records[i].dateOfPreparation, //订单日期
            // supplier: res.result.records[i].supplierId_dictText, //供应商
            // supplierId: res.result.records[i].supplierId, //供应商id
            // cwarehouseid_dictText: res.result.records[i].cwarehouseid_dictText,
            // cwarehouseid: res.result.records[i].cwarehouseid,
            // pkCalbody_dictText: res.result.records[i].pkCalbody_dictText,
            // cbiztype: res.result.records[i].cbiztype,
            // cbiztype_dictText: res.result.records[i].cbiztype_dictText,
          };
          console.log("----- data -----", data);
          this.orderDataSource.push(data);
        }
      });
    },

    // 展示对话框
    showModal() {
      console.log("");
      this.stockNoticeShowType = true;
      this.getDeparmentTree(); // 获取部门树
      this.generateSourceList_back(); //获取采购订单列表

      this.visible = true;
    },
    // 提交
    handleOk() {
      console.log("提交");

      this.$emit("origin-data", this.originData); //将子组件的数据，传递到父组件
      this.$emit("origin-data2", this.originData2); //将子组件的数据，传递到父组件

      this.orderSelectedRowKeys = []; //上方table按钮
      this.listSelectedRowKeys = []; //下方table按钮
      this.ListDataSource = []; //下方rable重置

      //查现存
      let data = {
        sourceNumber: this.savesourceNumber,
        inventoryId: this.saveinventoryId,
      };
      cgrkHttp.getBalanceInOutStockBySourceNumber(data).then((res) => {
        console.log("现存", res);
        // this.$emit("balance", res.result.balance);
      });

      this.visible = false;
      // this.$emit("select-data", this.SelectData);
    },
    // 清空
    Empty() {
      // this.ListDataSource = [];
      console.log("清空");
    },
    // 取消
    handleCancel() {
      this.visible = false;
    },

    // 根据业务需求,自己添加相应的样式和函数
    // 部门按钮触发
    DepartmentChange(value, option) {
      this.searchForm.departmentId = option.key;
    },

    // 获取销售订单列表

    // ----------- 用于备货通知单独有的 -----------
    // 获取部门列表
    getDeparmentTree() {
      comHttp.getDepartmentList().then((res) => {
        // let tree = this.resetTree(res.result);
        // console.log("获取部门树::::",tree);
        this.deparmentList = res.result;
        this.resetTree(this.deparmentList);
      });
    },
    // 树节点的 value值 变成 title,为了加上搜索框.
    resetTree(Tree) {
      Tree.forEach((item) => {
        item.value = item.title;
        if (item.children) {
          this.resetTree(item.children);
        }
      });
    },
    // 部门下拉框选择
    changeTreeNode(value, label, extra) {
      this.searchForm.departmentNo = extra.triggerNode.eventKey;
      console.log("选择的值::::", this.searchForm.departmentNo);
    },
    // 获取备货通知单列表
    getStockNoticeList() {
      console.log("获取当前备货通知单列表:::");
    },
    //禁止选择的组件
    getCheckboxProps(record) {
      return {
        props: {
          disabled: record.documentClosed === "关闭",
        },
      };
    },
  },
};
</script>

<style></style>
